package com.mail;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;

import com.sun.mail.pop3.POP3SSLStore;

public class GmailPopMail {

	private static final String user = "qazyncro@gmail.com";
	
	private static final String password = "qazyncroqazyncro ";
	
	private static Session session;
	
	static{
		
		Properties props = System.getProperties();
		props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.pop3.socketFactory.fallback", "false");
		props.setProperty("mail.pop3.port", "995");
		props.setProperty("mail.pop3.socketFactory.port", "995");
		props.setProperty("mail.pop3.host", "pop.gmail.com");
		props.setProperty("mail.pop3.user", user);
		props.setProperty("mail.pop3.passwd", password);
		props.setProperty("mail.pop3.ssl", "true");	
		
		session = Session.getInstance(props,null);
	}
	
	private Store store;
	
	public GmailPopMail(String email, String password){
		
		try {
			URLName urln = new URLName("pop3","pop.gmail.com",995,null, user, password);
			store = new POP3SSLStore(session, urln);
			store.connect("pop.gmail.com", email, password);
		
		} catch (MessagingException e) {
			throw new IllegalStateException(String.format("Could not connect to to gmail with user '%s'/'%s'", email, password),e);
		}
		
	}
	
	public Message[] getMessages(){
		try {
			
			Folder inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			return inbox.getMessages();
		
		} catch (MessagingException e) {
			throw new IllegalStateException("Couldn't get gmail messages",e);
		}
	}
	
	public List<Message> getMessagesWithSubject(String subject){
	
		Message[] messages = getMessages();
		
		List<Message> messagesList = new ArrayList<Message>();
		
		try{
			
			for (int i = 0; i < messages.length; i++) {
				if(messages[i].getSubject().equals(subject)){
					messagesList.add(messages[i]);
				}
			}
			return messagesList;
		}catch (MessagingException e) {
			throw new IllegalStateException("Couldn't get gmail message subject",e);
		}
		
	}
		
	 public static String getLinkMessage(Message message, String partialLink){
		
		 try{
			
			 String link = null;
			 
			 Part messagePart = message;
	         InputStream is = messagePart.getInputStream();
	         
	         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	         String thisLine = reader.readLine();

	         while (thisLine != null){
	        	 Pattern pattern = Pattern.compile("<a.*>" + partialLink + ".*</a>");
	        	 Matcher m = pattern.matcher(thisLine);
	        	
	        	 if (m.find()){
	        		link = thisLine.split(">")[1].replace("</a", "");
	        	 }
	        	 thisLine = reader.readLine();
	        }
	        
	        if(link != null){
	              
	        	return link;
	        }else
	        	throw new IllegalStateException("Couldn't find link in message"); 
	    }
	    catch (Exception e){
	      
	    	throw new IllegalStateException("Couldn't find link in message", e);
	    }
	    
	 }
}
